﻿using System;
using System.Collections;
using System.Collections.Generic;

class LargestAreaOfElements
{
    static string[,] bestSequence;
    static int countOfBestSequence;
    static string[,] array = 
    {
        { "1", "3", "2", "2", "2", "4" },
        { "3", "3", "3", "2", "4", "4" },
        { "4", "3", "1", "2", "3", "3" },
        { "4", "3", "1", "3", "3", "1" },
        { "4", "3", "3", "3", "1", "1" },
    };

    static void Main()
    {
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                List<string> list = new List<string>();
                list.Add(array[i, j]);
                MaximumSum(i, j, 1);
            }
        }
        Console.WriteLine("Longest sequence consists of {0} members", countOfBestSequence);
        Console.WriteLine("The sequence is:");
        Print(bestSequence);
    }

    private static void MaximumSum(int indexX, int indexY, int counter)
    {
        string currentItem = array[indexX, indexY];
        array[indexX, indexY] = "*";
        for (int i = -1; i <= 1; i++)
        {
            for (int j = -1; j <= 1; j++)
            {
                if (isInRange(array, indexX + i, indexY + j))
                {
                    if (array[indexX + i, indexY + j] == currentItem)
                    {
                        counter++;
                        MaximumSum(indexX + i, indexY + j, counter);
                        counter--;
                    }
                }
                else
                {
                    if (counter > countOfBestSequence)
                    {
                        countOfBestSequence = counter;
                        bestSequence = (string[,])array.Clone();
                        counter = 0;
                    }
                }
            }
        }
        array[indexX, indexY] = currentItem;
    }

    static bool isInRange(IEnumerable[,] array, int indexX, int indexY)
    {
        if (indexX < array.GetLength(0) && indexX >= 0 && indexY < array.GetLength(1) && indexY >= 0)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

    static void Print(string[,] array)
    {
        for (int i = 0; i < array.GetLength(0); i++)
        {
            for (int j = 0; j < array.GetLength(1); j++)
            {
                Console.Write(" " + array[i, j]);
            }
            Console.WriteLine();
        }
    }
}